package com.github.ilioili.justdoit.components.activity;


import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.CalendarContract;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CompoundButton;

import com.github.ilioili.justdoit.R;
import com.github.ilioili.justdoit.common.AppBaseActivity;
import com.github.ilioili.justdoit.common.config.AppConfig;
import com.github.ilioili.justdoit.common.config.Colors;
import com.github.ilioili.justdoit.common.config.EventConstants;
import com.github.ilioili.justdoit.common.config.UserInfo;
import com.github.ilioili.justdoit.model.dao.ScheduleEventDao;
import com.github.ilioili.justdoit.model.pojo.ScheduleEvent;
import com.github.ilioili.justdoit.util.CompatUtil;
import com.github.ilioili.justdoit.util.DateUtil;
import com.github.ilioili.justdoit.util.QiniuUtil;
import com.github.ilioili.justdoit.util.SwipeRefreshLayoutUtil;
import com.github.ilioili.justdoit.util.sql.DbUtil;
import com.github.ilioili.qqlogin.QqLoginBridgeActivity;
import com.taihe.template.base.injection.Id;
import com.taihe.template.base.injection.Layout;
import com.taihe.template.base.util.ToastUtil;

@Layout(R.layout.activity_settings)
public class SettingsActivity extends AppBaseActivity {
    private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 110;
    @Id(R.id.toolbar)
    private Toolbar toolbar;
    @Id(R.id.switch_gesture_lock)
    private SwitchCompat switchGesture;
    @Id(R.id.switch_vibrate)
    private SwitchCompat switchVibrate;
    @Id(R.id.swipeRefreshLayout)
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        SwipeRefreshLayoutUtil.initStyle(swipeRefreshLayout);
        switchGesture.setChecked(AppConfig.isGestureOn());
        switchVibrate.setChecked(AppConfig.isVibrateOn());
        switchGesture.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                AppConfig.setGesture(isChecked);
                updateGestureCodeItemVisibility();
            }
        });
        switchVibrate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                AppConfig.setVibrate(isChecked);
            }
        });
        updateGestureCodeItemVisibility();
    }

    private void updateGestureCodeItemVisibility() {
        if (AppConfig.isGestureOn()) setVisiable(R.id.item_set_gesture_code, R.id.gesture_divider);
        else setGone(R.id.item_set_gesture_code, R.id.gesture_divider);
    }

    public void onClickSetGesture(View v) {
        switchGesture.setChecked(!switchGesture.isChecked());
    }

    public void onClickSetGestureCode(View v) {
        ToastUtil.showLongToast(getString(R.string.feature_on_the_way));
    }

    public void onClickSetVibrate(View v) {
        switchVibrate.setChecked(!switchVibrate.isSelected());
    }

    public static Intent newIntent(Context context) {
        return new Intent(context, SettingsActivity.class);
    }

    public void onClickShortCut(View v) {
        final Intent addIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        final Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_create); // 获取快捷键的图标
        addIntent.putExtra("duplicate", false);
        final Intent myIntent = CreateOrModifyActivity.newIntent(this, EventConstants.TYPE_EVENT, 0, 0, CompatUtil.getColor(this, R.color.colorPrimary));
        myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.new_event));// 快捷方式的标题
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);// 快捷方式的图标
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myIntent);// 快捷方式的动作
        sendBroadcast(addIntent);
        Snackbar.make(v, R.string.snack_short_cut_success, Snackbar.LENGTH_SHORT).show();
    }

    public void onClickBackupToSdcard(final View v) {
        swipeRefreshLayout.setRefreshing(true);
        DbUtil.backupToSdcard();
        swipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                Snackbar.make(v, R.string.snack_data_backup_success, Snackbar.LENGTH_SHORT).show();
                swipeRefreshLayout.setRefreshing(false);
            }
        }, 1000);
    }

    public void onClickImportSdcardData(final View v) {
        swipeRefreshLayout.setRefreshing(true);
        DbUtil.restoreFromSdcard();

        swipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                Snackbar.make(v, R.string.snack_data_import_success, Snackbar.LENGTH_SHORT).show();
                swipeRefreshLayout.setRefreshing(false);
            }
        }, 1000);
    }

    public void onClickBackupToCloud(final View v) {
        if (checkLoginStaus()) {
            swipeRefreshLayout.setRefreshing(true);
            QiniuUtil.uploadDbFile(new QiniuUtil.Callback() {
                @Override
                public void onSuccess() {
                    Snackbar.make(v, "成功备份数据到云端", Snackbar.LENGTH_SHORT).show();
                    swipeRefreshLayout.setRefreshing(false);
                }

                @Override
                public void onFail() {
//                Snackbar.make(v, R.string.snack_data_backup_success, Snackbar.LENGTH_SHORT).show();
                    Snackbar.make(v, "ops 备份数据失败", Snackbar.LENGTH_SHORT).show();
                    swipeRefreshLayout.setRefreshing(false);
                }

                @Override
                public void onProgress(double percentage) {

                }
            });
        }
    }

    public void onClickRestoreFromCloud(final View v) {
        if (checkLoginStaus()) {
            QiniuUtil.downloadDbFile(Environment.getExternalStorageDirectory() + "/JustDoIt.db", new QiniuUtil.Callback() {
                @Override
                public void onSuccess() {
                    DbUtil.restoreFromSdcard();
                    swipeRefreshLayout.setRefreshing(false);
                    Snackbar.make(v, R.string.snack_data_import_success, Snackbar.LENGTH_SHORT).show();
                }

                @Override
                public void onFail() {

                }

                @Override
                public void onProgress(double percentage) {

                }
            });
        }
    }


    public void onClickImportCalendar(final View v) {
        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR)) {
            swipeRefreshLayout.setRefreshing(true);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String calanderEventURL = "content://com.android.calendar/events";
                        Cursor eventCursor = getContentResolver().query(Uri.parse(calanderEventURL), null, null, null, null);
                        while (eventCursor.moveToNext()) {
                            String eventTitle = eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events.TITLE));
                            long startTime = eventCursor.getLong(eventCursor.getColumnIndex(CalendarContract.Events.DTSTART));
                            long endTime = eventCursor.getLong(eventCursor.getColumnIndex(CalendarContract.Events.DTEND));
                            long createTime = eventCursor.getLong(eventCursor.getColumnIndex(CalendarContract.Events.ORIGINAL_INSTANCE_TIME));
                            boolean hasAlarm = eventCursor.getInt(eventCursor.getColumnIndex(CalendarContract.Events.HAS_ALARM)) == 1;
                            ScheduleEvent scheduleEvent = new ScheduleEvent();
                            scheduleEvent.createTime = createTime;
                            scheduleEvent.startTime = startTime;
                            scheduleEvent.color = Colors.getRandomColor();
                            scheduleEvent.endTime = endTime;
                            scheduleEvent.name = eventTitle;
                            scheduleEvent.id = startTime * 2;
                            scheduleEvent.alarm = hasAlarm;
                            scheduleEvent.isComplete = startTime < DateUtil.getTodayStartTime();
                            ScheduleEventDao.replace(scheduleEvent);
                        }
                        swipeRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Snackbar.make(swipeRefreshLayout, R.string.snack_data_import_success, Snackbar.LENGTH_SHORT).show();
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        }, 1000);
                    } catch (SecurityException e) {
                        swipeRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Snackbar.make(swipeRefreshLayout, R.string.snack_data_import_fail, Snackbar.LENGTH_SHORT).show();
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        }, 1000);
                    }

                }
            }).start();
        } else {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
                new AlertDialog.Builder(this).setTitle("需要读取系统日历的权限!").setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(SettingsActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
                    }
                });
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_READ_CONTACTS && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            onClickImportCalendar(null);
        } else {
            ToastUtil.showLongToast("权限都不给我, 还能不能愉快的玩耍儿了?");
        }
    }

    public void onClickDeleteAll(final View v) {
        Snackbar snackbar = Snackbar.make(v, R.string.snack_confim_clear_data, Snackbar.LENGTH_LONG);
        snackbar.setAction(R.string.confirm, new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                swipeRefreshLayout.setRefreshing(true);
                UserInfo.clear();
                DbUtil.clear();
                AppConfig.clear();
                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Snackbar.make(swipeRefreshLayout, R.string.snack_data_clear, Snackbar.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 1000);
            }
        });
        snackbar.show();
    }

    public boolean checkLoginStaus() {
        if (UserInfo.isLogin()) {
            return true;
        } else {
            Snackbar snackbar = Snackbar.make(swipeRefreshLayout, "是否要登陆帐号?", Snackbar.LENGTH_LONG);
            snackbar.setAction(R.string.confirm, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    QqLoginBridgeActivity.login(SettingsActivity.this, new QqLoginBridgeActivity.OnUserInfoListener() {
                        @Override
                        public void onUserInfoObtained(String name, String iconUrl, String id) {
                            UserInfo.setName(name);
                            UserInfo.setIconUrl(iconUrl);
                            UserInfo.setIsLogin(true);
                            UserInfo.setUserId(id);
                        }
                    });
                }
            });
            snackbar.show();
            return false;
        }
    }

}
